package com.fs.rpc.registry;

import com.fs.rpc.model.ServiceMetaInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RegistryServiceCache {

    /**
     * 服务缓存，key：serviceKey，value：serviceNodeKey：serviceMetaInfo
     */
    private final Map<String, Map<String, ServiceMetaInfo>> serviceCache = new ConcurrentHashMap<>();

    /**
     * 写缓存
     * @param serviceKey 服务键名
     * @param serviceNodeKey 服务节点键名
     * @param serviceMetaInfo 服务节点信息
     */
    public void writeCache(String serviceKey, String serviceNodeKey, ServiceMetaInfo serviceMetaInfo) {
        if (!serviceCache.containsKey(serviceKey)) {
            Map<String, ServiceMetaInfo> metaInfoMap = new HashMap<>();
            metaInfoMap.put(serviceNodeKey, serviceMetaInfo);
            serviceCache.put(serviceKey, metaInfoMap);
        } else {
            Map<String, ServiceMetaInfo> metaInfoMap = serviceCache.get(serviceKey);
            metaInfoMap.put(serviceNodeKey, serviceMetaInfo);
        }
    }

    /**
     * 读缓存
     * @param serviceKey 服务键名
     * @return
     */
    public List<ServiceMetaInfo> readCache(String serviceKey) {
        Map<String, ServiceMetaInfo> metaInfoMap = serviceCache.get(serviceKey);
        return metaInfoMap == null ? null : new ArrayList<>(metaInfoMap.values());
    }

    /**
     * 删除缓存
     * @param serviceKey 服务键名
     * @param serviceNodeKey 服务节点键名
     */
    public void removeCache(String serviceKey, String serviceNodeKey) {
        Map<String, ServiceMetaInfo> metaInfoMap = serviceCache.get(serviceKey);
        if (metaInfoMap == null) {
            return;
        }
        metaInfoMap.remove(serviceNodeKey);
    }

    public boolean containsCache(String serviceKey, String serviceNodeKey) {
        Map<String, ServiceMetaInfo> metaInfoMap = serviceCache.get(serviceKey);
        if (metaInfoMap == null) {
            return false;
        }
        return metaInfoMap.containsKey(serviceNodeKey);
    }

    public boolean containsKey(String serviceKey) {
        return serviceCache.containsKey(serviceKey);
    }

}
